<template>
  <!---资产详情-->
  <div class="monitor-asset-info" ref="monitorAsset">
    <div class="asset-info-content">
      <div class="asset-info-header">
        <div class="header-01">
          <div
            class="report-state"
            :class="
              reportResult?.monitorState == 0 ? 'monitor-end' : 'monitor-start'
            "
          >
            {{ reportResult?.monitorState == 0 ? "监控结束" : "监控中" }}
          </div>
          <div class="report-id">
            <span>编</span>{{ reportResult?.identifier }}
          </div>
          <div
            class="export-report"
            @click="printReport(reportResult?.identifier)"
          >
            导出报告
          </div>
        </div>
        <div class="header-02">
          <div class="vin">{{ reportResult?.vin }}</div>
          <div class="header-02-start">
            [开始时间: {{ reportResult?.createdAt }}]
          </div>
        </div>
      </div>
      <el-divider />
      <!--基本信息，贷款信息-->
      <div class="content-01">
        <div class="content-01-left">
          <div class="baisc-info">
            <div class="info-title"><span></span>基本信息</div>
            <div class="baisc-info-01">
              <div class="baisc-info-line">
                <div class="left">品牌:</div>
                <div class="middle">{{ reportResult?.brandName }}</div>
              </div>
              <div class="baisc-info-line">
                <div class="left">车架号:</div>
                <div class="middle">{{ reportResult?.vin }}</div>
              </div>
              <div class="baisc-info-line">
                <div class="left">车型:</div>
                <div class="middle">
                  <div>
                    {{ reportResult?.carModel }}
                  </div>
                  <div v-if="!reportResult?.carNameEqual">
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      :content="reportResult?.carName"
                      placement="right-start"
                    >
                      <el-icon color="red" size="18" style="margin-top: 10px"
                        ><Warning
                      /></el-icon>
                    </el-tooltip>
                  </div>
                </div>
                <div class="right">
                  指导价：{{ reportResult?.newCarGuidePrice }}万
                </div>
              </div>
            </div>
          </div>
          <div class="baisc-info">
            <div class="info-title"><span></span>贷款信息</div>
            <div class="baisc-info-01">
              <div class="baisc-info-line">
                <div class="left">借款人:</div>
                <div class="middle">
                  {{ reportResult?.name }} {{ reportResult?.cardId }}
                  {{ reportResult?.phone }}
                </div>
              </div>
              <div class="baisc-info-line">
                <div class="left">金额:</div>
                <div class="middle">
                  {{ reportResult?.loanAmount }}万元 （{{
                    reportResult?.term
                  }}期 月均{{ reportResult?.monthlyRent }}元）
                </div>
                <div class="right">
                  落地价：{{ reportResult?.transactionPrice }}万
                </div>
              </div>
              <div class="baisc-info-line">
                <div class="left">申请时间:</div>
                <div class="middle">{{ reportResult?.applyDate }}</div>
                <div class="right">
                  交车时间： {{ reportResult?.deliveryDate }}
                </div>
              </div>
              <div class="baisc-info-line">
                <div class="left">首期还款日期:</div>
                <div class="middle">{{ reportResult?.firstRepaymentDate }}</div>
              </div>
            </div>
          </div>
          <div class="baisc-info" style="margin-top: -20px">
            <div class="baisc-info-01">
              <div class="baisc-info-line">
                <div class="left">机构渠道:</div>
                <div class="middle">{{ reportResult?.spName }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="content-01-right">
          <div class="content-01-right-01">
            <!-- 右侧风险状态区 -->
            <!-- 红绿灯状态图标 -->
            <div class="flex flex-col items-center mb-4">
              <div class="bg-gray-200 rounded-full">
                <!-- 红灯 -->
                <div
                  class="rounded-full bg-red-500"
                  :class="reportResult?.riskLevel == 3 ? 'current-risk' : ''"
                ></div>
                <!-- 黄灯 -->
                <div
                  class="rounded-full bg-yellow-500"
                  :class="reportResult?.riskLevel == 2 ? 'current-risk' : ''"
                ></div>
                <!-- 绿灯 -->
                <div
                  class="rounded-full bg-green-500"
                  :class="reportResult?.riskLevel == 1 ? 'current-risk' : ''"
                ></div>
              </div>
            </div>

            <!-- 状态提示文字 -->
            <div class="text-center">
              <p
                class="text-green-600 font-medium"
                v-if="reportResult?.riskLevel == 0"
                style="color: #22c55e"
              >
                当前状态：无风险
              </p>
              <p
                class="text-green-600 font-medium"
                v-if="reportResult?.riskLevel == 1"
                style="color: #22c55e"
              >
                当前状态：低风险
              </p>
              <p
                class="text-green-600 font-medium"
                v-if="reportResult?.riskLevel == 2"
                style="color: rgb(245, 154, 36)"
              >
                当前状态：中风险
              </p>
              <p
                class="text-green-600 font-medium"
                v-if="reportResult?.riskLevel == 3"
                style="color: rgb(222, 41, 16)"
              >
                当前状态：高风险
              </p>
            </div>
          </div>
          <div class="content-01-right-02">
            <div class="xh">
              <div class="xh-number">{{ reportResult?.totalRisk }}</div>
              <div class="xh-tilte">信号总数</div>
            </div>
            <div class="level-desc">
              <div class="level-line">
                <img src="../assets/risklevel-h.svg" />
                <div class="desc">高风险: {{ reportResult?.highRisk }}</div>
              </div>
              <div class="level-line">
                <img src="../assets/risklevel-m.svg" />
                <div class="desc">中风险: {{ reportResult?.mediumRisk }}</div>
              </div>
              <div class="level-line">
                <img src="../assets/risklevel-l.svg" />
                <div class="desc">低风险: {{ reportResult?.lowRisk }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!---监控信息-->
      <div class="content-02">
        <div class="content-02-header"><span></span>监控信息</div>
        <div class="rili" id="rili"></div>
      </div>
      <!--规则展示-->
      <div style="width: 99%; padding-left: 10px; padding-bottom: 100px">
        <!-- <el-timeline>
          <el-timeline-item
            :timestamp="item.riskDate"
            placement="top"
            type="primary"
            v-for="(item, index) in riskInfoList"
            :key="index"
          >
            <div class="rule-show" v-for="(rule, i) in item.riskList" :key="i">
              <div class="rule-name">
                <div class="rule-image rule-image-h" v-if="rule.riskLevel == 1">
                  高风险
                </div>
                <div class="rule-image rule-image-m" v-if="rule.riskLevel == 2">
                  中风险
                </div>
                <div class="rule-image rule-image-l" v-if="rule.riskLevel == 3">
                  低风险
                </div>
                <div class="rule-name-01">
                  {{ rule.ruleName }}
                </div>
                <div class="disposal ending-disposal" v-if="rule.riskDisposal">
                  待处置
                </div>
                <div class="disposal rocessed" v-if="!rule.riskDisposal">
                  已处置：无风险
                </div>
              </div>
              <div class="rule-desc">{{ rule.riskDesc }}</div>
            </div>
          </el-timeline-item>
        </el-timeline> -->

        <el-table
          :data="reportResult?.riskInfoList"
          stripe
          border
          :header-cell-style="tableHeaderColor"
          :cell-style="cellStyle"
        >
          <el-table-column prop="createdAtFormatted" label="触发时间" />
          <el-table-column prop="ruleName" label="规则名称" />

          <el-table-column prop="riskDetail" label="规则描述" />
          <el-table-column label="风险等级">
            <template #default="scoped">
              <div
                style="color: rgb(222, 41, 16)"
                v-if="scoped.row.riskLevel === 3"
              >
                高风险
              </div>
              <div
                style="color: rgb(245, 154, 36)"
                v-if="scoped.row.riskLevel === 2"
              >
                中风险
              </div>
              <div
                style="color: rgb(123, 123, 250)"
                v-if="scoped.row.riskLevel === 1"
              >
                低风险
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { useRoute } from "vue-router";
import http from "@/request/request";
import { Warning } from "@element-plus/icons-vue";
import html2canvas from "html2canvas";

const route = useRoute();
let monitorAsset = ref(null);
// table样式
const tableHeaderColor = {
  background: "rgb(245, 248, 250) !important",
  color: "rgb(51, 51, 51)",
  "text-align": "center",
};
const cellStyle = {
  "text-align": "center",
};
//------------------------------------变量------------------------------------//
interface Risk {
  ruleId: number;
  riskLevel: number;
  ruleName: string;
  riskDetail: string;
  createdAtFormatted: string;
}
interface ReportResult {
  id: number;
  orgId: number;
  monitorState: number;
  identifier: string;
  vin: string;
  carModel: string;
  newCarGuidePrice: number;
  transactionPrice: number;
  name: string;
  phone: string;
  cardId: string;
  loanAmount: number;
  term: number;
  monthlyRent: number;
  applyDate: string;
  deliveryDate: string;
  firstRepaymentDate: string;
  spName: string;
  riskLevel: number;
  riskLevelDesc: string;
  brandName: string;
  carName: string;
  carNameEqual: boolean;
  identifyNewCarPrice: number;
  identifyRetail: number;
  riskInfoList: Risk[];
  totalRisk: number;
  highRisk: number;
  mediumRisk: number;
  lowRisk: number;
  createdAt: string;
  riskInfoListByLocalDate?: {
    [propName: string]: {
      [propName: string]: Risk[];
    };
  };
}

const reportResult = ref<ReportResult>();

// 计算echats的series
const getSeries = () => {
  const seriesList = [];
  const calendarList = [];
  const riskInfoListByLocalDate = reportResult.value?.riskInfoListByLocalDate;
  if (riskInfoListByLocalDate) {
    let top = 50;
    let calendarIndex = 0;
    for (let key in riskInfoListByLocalDate) {
      const series = {
        type: "heatmap",
        coordinateSystem: "calendar",
        calendarIndex,
        label: {
          show: true,
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          formatter: function (params: any) {
            var d = echarts.number.parseDate(params.value[0]);
            return d.getDate();
          },
          color: "rgba(51, 51, 89,0.2)",
        },
        data: getVirtualData(key, riskInfoListByLocalDate[key]),
      };
      const calendar = {
        top,
        left: 60,
        right: 30,
        cellSize: 16,
        range: key,
        itemStyle: {
          borderWidth: 0.5,
          borderColor: "#ded7d6",
        },
        yearLabel: { show: true },
      };
      calendarList.push(calendar);
      seriesList.push(series);
      top = top + 200;
      calendarIndex = calendarIndex + 1;
    }
    initTable(seriesList, calendarList);
  }
};

const getVirtualData = (
  year: string,
  riskInfoYear: { [propName: string]: Risk[] }
) => {
  const date = +echarts.time.parse(year + "-01-01");
  const end = +echarts.time.parse(+year + 1 + "-01-01");
  const dayTime = 3600 * 24 * 1000;
  const data = [];
  for (let time = date; time < end; time += dayTime) {
    let riskLevel = 0;
    let riskName = "";
    if (riskInfoYear && Object.keys(riskInfoYear).length != 0) {
      const riskInfo =
        riskInfoYear[echarts.time.format(time, "{yyyy}-{MM}-{dd}", false)];
      if (riskInfo) {
        riskLevel = Math.max(...riskInfo.map((r) => r.riskLevel));
        riskName = riskInfo.map((r) => r.ruleName).join(";");
      }
    }
    let color = null;
    if (riskLevel === 3) {
      color = "red";
    } else if (riskLevel === 2) {
      color = "#f59a24";
    } else if (riskLevel === 1) {
      color = "#6d7cf4";
    } else {
      color = "#fff";
    }
    data.push({
      value: [echarts.time.format(time, "{yyyy}-{MM}-{dd}", false), riskLevel],
      name:
        echarts.time.format(time, "{yyyy}-{MM}-{dd}", false) + ";" + riskName,
      itemStyle: {
        color: color,
      },
    });
  }
  return data;
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const initTable = (data: any, calendar: any) => {
  var chartDom = document.getElementById("rili");
  if (!chartDom) {
    return;
  }

  chartDom.style.height = data.length * 200 + "px";
  var myChart = echarts.init(chartDom);
  var option = {
    title: {
      // show: false,
      top: 30,
      left: "center",
      // text: "Daily Step Count",
    },
    tooltip: {
      trigger: "item", // 或者 'axis'，根据需求选择
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      formatter: function (params: any) {
        if (!params.name || params.name.length == 0) {
          return "";
        }
        const list = params.name.split(";");

        let str = `<div><div> ${list[0]} </div><ul style='margin-left: -20px;'>`;
        for (var i = 1; i < list.length; i++) {
          str = str + "<li>" + list[i] + "</li>";
        }
        str = str + "</ul></div>";
        // 方式1：直接使用换行符
        return `${str}`;

        // 方式2：更复杂的格式化
        // return `名称: ${params.name}\n\n详细信息:\n- X轴: ${params.data[0]}\n- Y轴: ${params.data[1]}\n- 数值: ${params.data[2]}`;
      },
    },
    visualMap: {
      min: 0,
      max: 3,
      calculable: true,
      orient: "horizontal",
      left: "center",
      top: "top",
      show: false,
    },
    calendar: calendar,
    series: data,
  };
  option && myChart.setOption(option);
};
// 打印报告
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const printReport = (id: any) => {
  const element = monitorAsset.value;
  if (element === null) {
    return;
  }

  html2canvas(element)
    .then((canvas) => {
      const imgData = canvas.toDataURL("image/png");
      const printWindow = window.open("");

      if (printWindow == null) {
        return;
      }

      // 创建完整的HTML文档结构
      const htmlContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <title>租后报告-${id}</title>
          <style>
            body { 
              margin: 0; 
              padding: 0; 
              display: flex; 
              justify-content: center; 
              align-items: start;
              min-height: 100vh;
            }
            img { 
              max-width: 100%; 
              height: auto; 
              display: block;
            }
          </style>
        </head>
        <body>
          <img src="${imgData}" onload="window.print()" />
        </body>
      </html>
    `;

      // 写入完整文档
      printWindow.document.open();
      printWindow.document.write(htmlContent);
      printWindow.document.close();

      // 添加打印后关闭的逻辑
      printWindow.onafterprint = () => {
        setTimeout(() => {
          printWindow.close();
        }, 100);
      };

      // 备用方案：如果onafterprint不支持，设置超时关闭
      setTimeout(() => {
        if (!printWindow.closed) {
          printWindow.close();
        }
      }, 5000); // 5秒后强制关闭
    })
    .catch((error) => {
      console.error("截图生成失败:", error);
    });
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getReport = async (id: any) => {
  try {
    const { data } = await http.get<ReportResult>("/api/after-loan/report", {
      id,
    });

    reportResult.value = data;
    getSeries();
  } catch (err) {
    console.log(err);
  }
};
//----------------------------------------------生命周期------------------------//
onMounted(() => {
  const reportId = route.query.id;
  getReport(reportId);
});
</script>

<style lang="less" scoped>
.monitor-asset-info {
  background-color: rgb(240, 242, 245);
  .asset-info-content {
    width: 94%;
    margin-left: 3%;
    background-color: rgb(255, 255, 255);
    .asset-info-header {
      padding: 10px;
      .header-01 {
        display: flex;
        gap: 10px;
        .report-state {
          height: 16px;
          width: 56px;
          font-size: 12px;
          line-height: 16px;
          color: #fff;
        }
        .monitor-start {
          background-color: rgb(0, 128, 255);
        }
        .monitor-end {
          background-color: rgb(222, 41, 16);
        }
        .report-id {
          display: flex;
          height: 16px;
          width: 150px;
          background-color: rgb(250, 205, 145);
          font-size: 12px;
          line-height: 16px;
          span {
            display: block;
            color: #fff;
            margin-right: 4px;
            width: 20px;
            height: 16px;
            background-color: rgb(184, 116, 26);
          }
        }
        .export-report {
          width: 130px;
          height: 24px;
          background-color: rgb(222, 41, 16);
          color: #fff;
          border-radius: 4px;
          font-size: 14px;
          line-height: 24px;
          margin-left: 78%;
          cursor: pointer;
        }
      }
      .header-02 {
        display: flex;
        height: 40px;
        .vin {
          font-size: 24px;
          font-weight: 900;
        }
        .header-02-start {
          font-size: 14px;
          margin-left: 66%;
          line-height: 40px;
        }
      }
    }
    .el-divider--horizontal {
      margin: 0;
    }
    .content-01 {
      display: flex;
      .content-01-left {
        width: 79%;
        .baisc-info {
          padding: 10px;
          .info-title {
            display: flex;
            height: 16px;
            line-height: 16px;
            span {
              display: block;
              width: 2px;
              background-color: rgb(0, 128, 255);
              margin-right: 10px;
            }
          }
          .baisc-info-01 {
            margin-top: 10px;

            background-color: rgb(242, 242, 242);
            padding-top: 10px;
            padding-bottom: 10px;
            .baisc-info-line {
              display: flex;
              height: 40px;
              line-height: 40px;

              .left {
                width: 14%;
                text-align: end;
              }
              .middle {
                width: 66%;
                text-align: start;
                margin-left: 10px;
                display: flex;
                gap: 10px;
              }
              .right {
                text-align: start;
                width: 20%;
              }
            }
          }
        }
      }
      .content-01-right {
        width: 21%;
        .content-01-right-01 {
          margin-top: 7%;
          width: 96%;
          height: 240px;
          border: 1px solid rgb(242, 242, 242);
          border-radius: 6px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          .mb-4 {
            /* 自动布局子元素 */
            width: 64px;
            height: 160px;
            /* 自动布局 */
            display: flex;
            flex-direction: column;
            align-items: center;
            flex-wrap: wrap;
            align-content: center;
            border-radius: 9999px;
            background: #e5e7eb;
            .rounded-full {
              margin-top: 6px;
              /* 自动布局子元素 */
              width: 40px;
              height: 40px;
              z-index: 0;
              border-radius: 9999px;
            }
          }
          /* 红绿灯样式 */
          .bg-red-500 {
            opacity: 0.2;
            background: linear-gradient(
                0deg,
                rgba(0, 0, 0, 0.001),
                rgba(0, 0, 0, 0.001)
              ),
              #ef4444;
            box-shadow: 0px 0px 8px 2px rgba(239, 68, 68, 0.6);
          }

          .bg-yellow-500 {
            opacity: 0.2;
            background: linear-gradient(
                0deg,
                rgba(0, 0, 0, 0.001),
                rgba(0, 0, 0, 0.001)
              ),
              #eab308;
            box-shadow: 0px 0px 8px 2px rgba(234, 179, 8, 0.6);
          }

          .bg-green-500 {
            opacity: 0.2;
            background: linear-gradient(
                0deg,
                rgba(0, 0, 0, 0.001),
                rgba(0, 0, 0, 0.001)
              ),
              #22c55e;
            box-shadow: 0px 0px 8px 2px rgba(34, 197, 94, 0.6);
          }
          .current-risk {
            opacity: 1;
          }
          .level {
            width: 100%;
            position: relative;
            font-size: 58px;
            color: rgb(140, 140, 140);
            margin-top: -40%;
          }
          .text {
            position: relative;
            color: rgb(140, 140, 140);
            font-size: 14px;
            margin-top: 12%;
          }
        }
        .content-01-right-02 {
          display: flex;
          margin-top: 10px;
          .xh {
            width: 44%;
            height: 200px;
            background-color: rgb(242, 242, 242);
            .xh-number {
              height: 140px;
              line-height: 140px;
              font-size: 30px;
              font-weight: 900;
            }
          }
          .level-desc {
            width: 52%;
            border: 1px solid rgb(242, 242, 242);
            padding-top: 16px;
            .level-line {
              padding-left: 40px;
              padding-top: 20px;
              display: flex;
              gap: 10px;
              img {
                height: 30px;
                width: 26px;
              }
            }
          }
        }
      }
    }
    .content-02 {
      padding-left: 10px;
      .content-02-header {
        display: flex;
        height: 16px;
        line-height: 16px;
        span {
          display: block;
          width: 2px;
          background-color: rgb(0, 128, 255);
          margin-right: 10px;
        }
      }
      .rili {
        width: 100%;
        min-height: 200px;
      }
    }
  }
}
.rule-show {
  width: 100%;
  .rule-name {
    display: flex;
    height: 30px;
    margin-top: 10px;
    .rule-image {
      width: 60px;
      height: 20px;
      color: #fff;
      line-height: 20px;
      margin-right: 10px;
      background-size: cover; /* 让背景图片覆盖整个元素，同时保持图片的宽高比 */
      background-position: center; /* 背景图片居中显示 */
      background-repeat: no-repeat; /* 背景图片不重复 */
    }
    .rule-image-h {
      background-image: url("/src//assets/indicator-h.png");
    }
    .rule-image-m {
      background-image: url("/src//assets/indicator-m.png");
    }
    .rule-image-l {
      background-image: url("/src//assets/indicator-l.png");
    }
    .rule-name-01 {
      width: 73.5%;
      text-align: start;
    }
    .disposal {
      width: 20%;
      text-align: end;
    }
    .ending-disposal {
      color: #0080ff;
    }
    .rocessed {
      color: rgb(140, 140, 140);
    }
  }
  .rule-desc {
    height: 30px;
    width: 98%;
    text-align: left;
    line-height: 30px;
    padding-left: 10px;
    background-color: rgb(242, 242, 242);
  }
}

::v-deep(.el-timeline-item__timestamp) {
  margin-left: -96%;
  color: #000;
}
</style>